#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;
struct _dist{
int distance=0;
vector<int> pre_root;
bool check(int point){
return find(pre_root.begin(), pre_root.end(), point)==pre_root.end();
}
};
void find_route(vector<vector<int>>& edges, int point1, const int point2, _dist dd, int& dist){
if(point1==point2){
dist=dd.distance<dist? dd.distance: dist;
return;
}
for(int i=0; i<edges.size(); ++i){
if(edges[i][0]==point1 && dd.check(edges[i][1])){
_dist tmp=dd;
tmp.distance++;
tmp.pre_root.push_back(point1);
find_route(edges, edges[i][1], point2, tmp, dist);
} else if (edges[i][1]==point1 && dd.check(edges[i][0])){
_dist tmp=dd;
tmp.distance++;
tmp.pre_root.push_back(point1);
find_route(edges, edges[i][0], point2, tmp, dist);
}
}
}
ll solution(vector<int> a, vector<vector<int>> edges){
ll answer=0, zeros_count=0, sum;
for(int aa: a){
if(aa) zeros_count++;
answer+=aa;
}
if(zeros_count==a.size()) return 0;
if(answer) return -1;
for(int i=0; i<a.size(); ++i){
sum=0;
for(int j=0; j<a.size(); ++j){
if(i==j) continue;
int dist=a.size();
_dist dd;
find_route(edges, j, i, dd, dist);
sum+=dist*abs(a[j]);
}
if(!i) answer=sum;
else answer=answer>sum? sum: answer;
}
return answer;
}
int main(void){
vector<int> a1={-5, 0, 2, 1, 2};
vector<int> a2={0, 1, 0};
vector<vector<int>> edges1={
{0, 1}, {3, 4}, {2, 3}, {0, 3}
};
vector<vector<int>> edges2={
{0, 1}, {1, 2}
};
int result1=solution(a1, edges1);
int result2=solution(a2, edges2);
cout<<"Result1: "<<result1<<endl;
cout<<"Result2: "<<result2<<endl;
return 0;
}